// pages/activitys/join/join.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activityId: '',
    maxJoin: 0,
    activityPrice: 10,
    isTip: '',
    showTipBtn: false,
    tipIcon: '',
    tipText: '',
    gender: -1,
    genders:['保密', '女', '男'],
    orderNo: '',
    paying: false,
    isCost: 0,
    cost: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      activityId: options.id,
      isCost: options.isCost,
      maxJoin: options.maxJoin,
      cost: options.cost
    });
    if(this.data.isCost != 0){
      this.setData({
        activityPrice: Number(options.cost) * 100
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //console.log('onReady');
    //this.loadSuccessImg ();
  },

  onShow: function(options) {
    // 标记：已经点击过支付
    if (this.data.paying) {
        let _that = this;
        let _url = app.globalData.apiServerUrl + '/pay/wx/check/' + this.data.orderNo;
        // 注意轮询判断或延时判断支付
        // 注意请求后端判断是否支付成功而非通过前端判断
        wx.request({
            method: 'POST',
            url: _url,
            success: response => {
              let _rd = response.data;
              if(_rd.code = 200 && _rd.status){
                if(_rd.data){
                  _that.setData({
                    isTip: 'Modal',
                    tipIcon: 'success',
                    tipText: '支付成功!',
                    showTipBtn: true
                  });
                } else {
                  _that.setData({
                    isTip: 'Modal',
                    tipIcon: 'warn',
                    tipText: '支付失败!',
                    showTipBtn: true
                  });
                }
              }else{
                _that.setData({
                  isTip: 'Modal',
                  tipIcon: 'cancel',
                  tipText: '支付异常!',
                  showTipBtn: true
                });
              }
                
            }
        });
    }

  },

  changeGender(e) {
    this.setData({
      gender: Number(e.detail.value)
    })
  },

  // 完成提交
  formSubmit(e) {
    let _that = this;
    let _fd = e.detail.value;
    if(!_fd.name){
      _that.showTipModal('提示', '请输入姓名');
      return false;
    }else if(!_fd.tel){
      _that.showTipModal('提示', '请输入联系电话');
      return false;
    }
    _that.getJoinUserList(_fd)
  },

  // 获取当前活动的参加人员列表
  getJoinUserList(_fd){
    let _that = this;
    let _url = app.globalData.apiServerUrl + '/join/user/' + this.data.activityId;
    wx.request({
      url: _url,
      success(res) {
        var _d = res.data;
        if(_d.code == 200 && _d.status){
          if(_d.data && _that.data.maxJoin <= _d.data.length){
            _that.setData({
              isTip: 'Modal',
              tipIcon: 'info',
              tipText: '活动已满员!',
              showTipBtn: true
            });
            //_that.showTipModal('提示', '抱歉,活动已满员!');
          }else{
            _that.join(_fd);
          }
        }
      }
    });
  },


  join(fd) {
    let _that = this;
    
    let _url = app.globalData.apiServerUrl + '/join';
    wx.request({
      url: _url,
      method: 'POST',
      data: {
        "userId": "",
        "activityId": this.data.activityId,
        "userName": fd.name,
        "gender": this.data.gender,
        "idCard": fd.idCard?fd.idCard:'',
        "tel": fd.tel,
        "openId": wx.getStorageSync('loginUserId')
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success (res) {
        let _rd = res.data;
        if(_rd.code = 200 && _rd.status){
          if(_that.data.isCost == 0){
            _that.setData({
              isTip: 'Modal',
              tipIcon: 'success',
              tipText: '报名成功!',
              showTipBtn: true
            });
          }else{
            _that.getPaySign();
          }
          
        }else{
          _that.showTipModal('提示', '活动报名失败!');
        }
      }
    });
  },

  getPaySign() {
    wx.showLoading({
      title: '执行中……',
    });
    let _that = this;
    let _url = app.globalData.apiServerUrl + '/pay/wx/paysign';
    wx.request({
      url: _url,
      method: 'POST',
      data: {
        "f": _that.data.activityPrice,
        "u": wx.getStorageSync('loginUserId'),
        "a": _that.data.activityId,
        "r": 'https://www.bkybk.com/app/v1/activityTools/pay/wx/payNotify'
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success (res) {        
        let _rd = res.data;
        if(_rd.code = 200 && _rd.status){
          _that.setData({
            orderNo: _rd.data['out_trade_no']
          });
          _that.toMiniPayProgram(_rd.data);
        }else{
          _that.showTipModal('提示', '活动报名异常!');
        }
      }
    });
  },
  

  

  toMiniPayProgram (param) {
    let _that = this;
    
    wx.navigateToMiniProgram({
      appId: 'wx959c8c1fb2d877b5',
      path: 'pages/pay',
      extraData: param,
      success: () => {
        //console.log('等待返回支付结果')
        wx.hideLoading();
        // 做已经点击过支付的标记
        _that.setData({
          paying: true,
          isTip: 'Modal',
          tipIcon: 'waiting',
          tipText: '支付中……',
          showTipBtn: false
        });
      },
      fail: () => {
        // 小程序跳转失败
        _that.setData({
          isTip: '',
          paying: false
        });
      }
    });
  },

  showTipModal(title, content) {
    wx.showModal({
      title: title,
      content: content,
      showCancel: false,
      success (res) {}
    });
  },

  // 确定跳转
  hideModal(e) {
    this.setData({
      isTip: ''
    });
    wx.redirectTo({
      url: '/pages/index/index'
    });
  },


  







})